package com.financing.platform.web.api;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.financing.platform.dto.*;
import com.financing.platform.service.*;
import com.financing.platform.util.*;
import com.financing.platform.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.platform.common.Pager;
import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;

@Controller("orderActionApi")
@RequestMapping("/api/order")
@Scope("prototype")
public class OrderAction  extends BaseAction{

	private ExecutorService es = Executors.newFixedThreadPool(5);
	
	@Autowired
	IOrderService orderServiceImpl;
	
	@Autowired
	IProjectService projectServiceImpl;
	
	@Autowired
	IFaUserService faUserServiceImpl;
	
	@Autowired
	IOrderPhoService orderPhoServiceImpl;
	
	@Autowired
	private IFaNoticeService faNoticeService;
	@Autowired
	private IFpFaUserContractService fpFaUserContractService;
	
	@Value("#{settings['orderPreTime']}")
	private String orderPreTime;
	
	@Autowired
	private IProjectAnnualRevenueService projectAnnualRevenueServiceImpl; 
	
	@Autowired
	private IProjectRabateService projectRabateSericeImpl;
	
	@Autowired
	private IYouDanAmountService youDanAmountServiceImpl;
	
	@Autowired
	private IClientService clientService;

    @Autowired
    private IFpOrderCostService fpOrderCostService;

	@Autowired
	private IBankCardService bankCardServiceImpl;
	
	@RequestMapping("/queryOrderList.shtml")
	@ResponseBody
	public ResultMap queryOrderList(HttpServletRequest request,
			HttpServletResponse response,OrderVO orderVo,Pager page) {
		
		try{
			if(orderVo.getSystemUserId() != null && !("").equals(orderVo.getSystemUserId()) && ("isnoManagerUser").equals(orderVo.getSystemUserId())){
				orderVo.setSystemUserId(null);
			}
			// 判断当前登录者是否是订单管理员
			HttpSession session = request.getSession();
			UserInfoDTO user = (UserInfoDTO)session.getAttribute(DTOdateSet.user);
			
			if(!"admin".equals(user.getUserNickname())){
				boolean isManager = false;
				List<AccessInfoDTO> accessInfoList = user.getAccessList();
				for(AccessInfoDTO access : accessInfoList){
					if(access.getActionName().equals("addManagerOrderUser.shtml")){
						isManager = true;
						break;
					}
				}
				if(!isManager){
					orderVo.setSystemUserId(user.getUserId());
				}
			}
			
			page.setTotalCount(orderServiceImpl.queryOrderAllInfoCount(orderVo));
			
			orderVo.setBegin(page.getStartIndex());
			orderVo.setEnd(page.getPageSize());
			List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);
			
			resultMap.setAttribute("orderList", listOrder);
			resultMap.setAttribute("page",page);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	
	@RequestMapping("/queryOrderByProIdList.shtml")
	@ResponseBody
	public ResultMap queryOrderByProIdList(HttpServletRequest request,
			HttpServletResponse response,OrderVO orderVo,Pager page) {
		try{
			page.setTotalCount(orderServiceImpl.countOrderByProIdList(orderVo));
			
			orderVo.setBegin(page.getStartIndex());
			orderVo.setEnd(page.getPageSize());
			List<HashMap<String, String>> listOrder = orderServiceImpl.queryOrderByProIdList(orderVo);
			
			resultMap.setAttribute("orderList", listOrder);
			resultMap.setAttribute("page",page);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	
	@RequestMapping("/queryOrderDetail.shtml")
	@ResponseBody
	public ResultMap queryOrderDetail(HttpServletRequest request,
			HttpServletResponse response,OrderVO orderVo ) {
		
		try{
			List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);
			
			if(listOrder.size()>0){
				orderVo = listOrder.get(0);
			} 
			
			resultMap.setAttribute("orderDetail", orderVo);
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		
		return resultMap;
	}
	
	@RequestMapping("/updateOrderStatus.shtml")
	@ResponseBody
	public ResultMap updateOrderStatus(HttpServletRequest request,
			HttpServletResponse response,OrderDTO orderDTO) {
		
		try{
			DTOdateSet.setUpdateInfo(orderDTO, request.getSession());
			
			// 订单如果附件没有审核成功，则不能修改确认返佣
			if(orderDTO.getoStatus()==320){
				
				OrderVO orderVo=new OrderVO();
				orderVo.setOrderId(orderDTO.getId());
				List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);
				if(listOrder.size()>0){
					orderVo = listOrder.get(0);
				}
				if(DateUtil.parseDateString(orderPreTime,"yyyy-MM-dd").before(orderVo.getCreateDate())){
					OrderPhoVO orderPhoVO=new OrderPhoVO();
					orderPhoVO.setoId(orderDTO.getId()+"");
					Map<String, Object> queryOrderPhoConfirm = orderPhoServiceImpl.queryOrderPhoConfirm(orderPhoVO);
					int fpodIdCount=Integer.parseInt(queryOrderPhoConfirm.get("fpodId")+"");
					int fopIdCount=Integer.parseInt(queryOrderPhoConfirm.get("fopId")+"");
					if(fpodIdCount!=fopIdCount){
						log.info("还有附件未通过审核!!!!");
						resultMap.setStatus(STATUS.FAILE);
						resultMap.setStatusCode(ResultCode.STATUS_CODE_ORDERCONFIRM_ERROR);
						return resultMap;
					}
				}
				
			}

			StringBuffer stringBuffer = new StringBuffer()
											.append("order ")
											.append(orderDTO.getId())
											.append("status update to ")
											.append(orderDTO.getoStatus());
			logsServiceImpl.addLog("updateOrderStatus order id :"+orderDTO.getId(), stringBuffer.toString(), orderDTO.getUpdateBy());
			
			if(orderServiceImpl.updateOrderStatus(orderDTO)<1){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}

			FaNoticeDTO notice = new FaNoticeDTO();
			DTOdateSet.setCreateInfo(notice, request.getSession());
			DTOdateSet.setUpdateInfo(notice, request.getSession());
			
			notice.setOrderId(orderDTO.getId());
			//设置标识判断  非空
			if(!StringUtils.isBlank(orderDTO.getShopperId())){
				notice.setJpushSource("shop");  //添加极光推送标识
				notice.setAppSource("shop");  //添加APP消息标识
			}
			
			// 状态修改成功后、添加通知消息
			log.info("状态修改成功后、添加通知消息:"+orderDTO.getoStatus());
			switch (orderDTO.getoStatus()) {
			case 130:
				// 130：预约成功；
				notice.setType("01");
				break;
			case 210:
				// 210：合同已寄出：
				notice.setType("02");
				break;
			case 140:
				// 140：预约失败：
				notice.setType("03");
				break;
			case 888:
				// 888：订单失败：
				notice.setType("04");
				break;
			case 240:
				// 240：确认打款：
				notice.setType("05");
				break;
			case 320:
				// 320：已返佣：
				notice.setType("06");
				break;
			case 321:
				// 321：已返佣(后端)：
				notice.setType("07");
				break;			
			case 360:
				// 360：交易结束：
				notice.setType("08");
				break;
			default:
				notice.setType("0");
				break;
			}
			if (!notice.getType().equals("0")) {
				faNoticeService.addFaOrderNotice(notice);
			}
			sendOrderNotice(orderDTO.getId(),orderDTO.getoStatus(),null, notice);
				
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("update order status error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	@RequestMapping("/updateOrderDefriendStatus.shtml")
	@ResponseBody
	public ResultMap updateOrderDefriendStatus(HttpServletRequest request,
			HttpServletResponse response,OrderDTO orderDTO) {
		
		try{
			log.info("in updateOrderDefriendStatus begin!");
			DTOdateSet.setUpdateInfo(orderDTO, request.getSession());
			if(orderServiceImpl.updateOrderDefriendStatus(orderDTO)<1){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			log.info("in updateOrderDefriendStatus end!");
		}catch(Exception e){
			log.error("update order DefriendStatus error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
				
	@RequestMapping("/queryOrderFollowUpList.shtml")
	@ResponseBody
	public ResultMap queryOrderFollowUpList(HttpServletRequest request,
			HttpServletResponse response,OrderVO orderVo,Pager page) {
		
		try{
			
			
			page.setTotalCount(orderServiceImpl.queryOrderFollowUpAllInfoCount(orderVo));
			
			orderVo.setBegin(page.getStartIndex());
			orderVo.setEnd(page.getPageSize());
			List<OrderVO> listOrder = orderServiceImpl.queryOrderFollowUpList(orderVo);
			
			resultMap.setAttribute("orderList", listOrder);
			resultMap.setAttribute("page",page);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	
	/**
	 * 订单流程改造
	 * 查询订单全部详情 包括核心成本价
	 */
	@RequestMapping("/queryOrderAllDetailByGaiZao.shtml")
	@ResponseBody
	public ResultMap  queryOrderAllDetailByGaiZao(HttpServletRequest request,HttpServletResponse response){
		try{
			// 入参校验
			String orderId = request.getParameter("id");
			if(StringUtil.isNullOrEmptyStr(orderId) || !StringUtil.isNumberStr(orderId)){
				log.error("queryOrderDetailByGaiZao check parameter:id error");
				resultMap.setStatus(STATUS.ERROR);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			OrderByGaiZaoDTO orderDTO = new OrderByGaiZaoDTO();
			// 判断当前登录者是否是订单管理员 
			HttpSession session = request.getSession();
			UserInfoDTO user = (UserInfoDTO)session.getAttribute(DTOdateSet.user);
			
			if(!"admin".equals(user.getUserNickname())){
				List<AccessInfoDTO> accessInfoList = user.getAccessList();
				for(AccessInfoDTO access : accessInfoList){
					//  部门判断
					if(access.getActionName().equals("isQuDao.shtml")){
						orderDTO.setDepartmentName(Dict.department_name_qudao);
					}
				}
			}
			// 查询订单
			orderDTO.setId(orderId);
			OrderByGaiZaoDTO queryOrderResult = orderServiceImpl.queryOrderDetailByGaiZao(orderDTO);
			// 如果结款类型为null，默认给01
			if(null == queryOrderResult.getoKnotType()){
				queryOrderResult.setoKnotType("01");
			}
//			// 如果是财务查询后端的详情，去除前端状态码
//			if(null != request.getParameter("orderCtrType") && "07".equals(request.getParameter("orderCtrType"))){
//				queryOrderResult.setoStatus(null);
//			}
			// 如果是财务查询我的有效订单详情，计算盈利值
			if(null != request.getParameter("orderCtrType") && "06".equals(request.getParameter("orderCtrType"))){
				queryOrderResult.calculateProfitAmount();
			}
			// 判断协议价字段是否存在
			if(null == queryOrderResult.getIsAgreement()){
				// 查询出对应产品收益率
				List<ProjectAnnualRevenueDTO> projectAccount =  projectAnnualRevenueServiceImpl.queryProjectAnnualRevenue(queryOrderResult.getoProjectId());
				ProjectRabateDTO  tempDTO = new ProjectRabateDTO();
				tempDTO.setpId(queryOrderResult.getoProjectId());
				List<ProjectRabateDTO>  projectRabateList = projectRabateSericeImpl.queryProjectRabate(tempDTO);
				// 判断在哪一区间
				for (ProjectAnnualRevenueDTO tempDto : projectAccount) {
					if(tempDto.getpStartAmount().intValue()<=queryOrderResult.getoAmount().intValue() && 
							queryOrderResult.getoAmount().intValue() < tempDto.getpEndAmount().intValue()){
						for (ProjectRabateDTO projectRabateDTO : projectRabateList) {
							if(projectRabateDTO.getArId().intValue() == tempDto.getId().intValue()){
								queryOrderResult.setIsAgreement(projectRabateDTO.getpIsAgreement());
							}
						}
					}
				}
				// 存入数据库
				OrderByGaiZaoDTO updateIsAgreementDTO = new OrderByGaiZaoDTO();
				updateIsAgreementDTO.setId(queryOrderResult.getId());
				updateIsAgreementDTO.setIsAgreement(queryOrderResult.getIsAgreement());
				orderServiceImpl.updateOrderStatusByGaiZao(updateIsAgreementDTO);
			}
			// 石柱判断成交价
			if(null == queryOrderResult.getoTransactionPrice()){
				queryOrderResult.setShiZhuFlag("0");
			}else{
				queryOrderResult.setShiZhuFlag("1");
			}
			// 查询该笔订单,如果是自提，查询出自提状态
			// 判断是否走到返佣阶段
			if(null != queryOrderResult.getoRebateType() || null != queryOrderResult.getoBackRebateType() || null != queryOrderResult.getoYouDanRebateType()){
				// 判断是否有佣金自提
				if("1".equals(queryOrderResult.getoRebateType()) || "1".equals(queryOrderResult.getoBackRebateType()) || "1".equals(queryOrderResult.getoYouDanRebateType())){
					//TODO
					List<YouDanAmountDTO> orderAmountList = youDanAmountServiceImpl.getCommonOrderAmountByAssociationId(queryOrderResult.getId());
					for (YouDanAmountDTO youDanAmountDTO : orderAmountList) {
						if("03".equals(youDanAmountDTO.getAmountType())){
							queryOrderResult.setoRebateOperateType(youDanAmountDTO.getOperateType());
						}else if("04".equals(youDanAmountDTO.getAmountType())){
							queryOrderResult.setoBackRebateOperateType(youDanAmountDTO.getOperateType());
						}else if("02".equals(youDanAmountDTO.getAmountType())){
							queryOrderResult.setoYouDanOperateType(youDanAmountDTO.getOperateType());
						}
					}
				}
			}
			// 返回
			resultMap.setAttribute("orderDetail", queryOrderResult);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order detail error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	/**
	 * 订单流程改造
	 * 查询订单详情 不包括核心、成本
	 */
	@RequestMapping("/queryOrderDetailByGaiZao.shtml")
	@ResponseBody
	public ResultMap  queryOrderDetailByGaiZao(HttpServletRequest request,HttpServletResponse response){
		ResultMap queryResult = this.queryOrderAllDetailByGaiZao(request, response);
		OrderByGaiZaoDTO queryOrderResult = (OrderByGaiZaoDTO) queryResult.getAttribute("orderDetail");
		queryOrderResult.resetCoreData();
		queryResult.setAttribute("orderDetail",queryOrderResult);
		return queryResult;
	}
	
	
	/**
	 * 订单流程改造
	 * 查询订单列表 基础
	 */
	@RequestMapping("/queryOrderListByGaiZao.shtml")
	@ResponseBody
	public ResultMap  queryOrderListByGaiZao(HttpServletRequest request,HttpServletResponse response,OrderByGaiZaoDTO orderDTO,Pager page){
		try{
			String orderSonCtrType = request.getParameter("orderSonCtrType");

			if(orderDTO.getoManagerId() != null && !("").equals(orderDTO.getoManagerId()) 
					&& ("isnoManagerUser").equals(orderDTO.getoManagerId())){
				orderDTO.setoManagerId(null);
			}

			//726ddlcyh-订单优化
			// 判断orderCtrType是后端还是前端
			/*if(null != orderDTO.getOrderCtrType() && null == orderDTO.getoStatus() && null == orderDTO.getoBackStatus()){
				if(orderDTO.getOrderCtrType().equals("03") || orderDTO.getOrderCtrType().equals("07")){
					orderDTO.setIsBackCtrType("Y");
				}else if(orderDTO.getOrderCtrType().equals("04") || orderDTO.getOrderCtrType().equals("08")){
					orderDTO.setIsSpecialCtrType("Y");
				}else{
					orderDTO.setIsFrontCtrType("Y");
				}
			}
			// 如果查询的是240已确认打款，兼容老数据，增加250状态
			if(null != orderDTO.getoStatus() && orderDTO.getoStatus() == 240){
				orderDTO.setoStatus(null);
				orderDTO.setoStatusCollection("240,250");
			}*/

			/*
			put( "qd_wwcdd" , "yyz,ddk,qddjy" );// 渠道 -未完成订单
			put( "qd_ywcdd" , "jiaoywc,jieywc" );//渠道-已完成订单
			put( "ddsb" , "ddsb" );//订单失败
			put( "cp_wwcdd" , "dqrdk,dqrjy" );// 产品 -未完成订单
			put( "cp_dshdd" , "dshdd" );// 产品 -待审核订单
			put( "cw_djy" , "djy" );// 财务 -待结佣
			*/

			String orderCtrType = orderDTO.getOrderCtrType();
			if(StringUtils.isBlank(orderCtrType) ){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			/*if(!Dict.frontPage_key.containsKey(orderCtrType) && !Dict.frontKey_order_status.containsKey(orderSonCtrType) ){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}*/

			//判断是否需要过滤后端状态
			//判断是否需要
			if(Dict.frontPage_isBack.containsKey(orderCtrType)) {
				if ("1".equals(Dict.frontPage_isBack.get(orderCtrType))) {
					orderDTO.setIsFrontCtrType("Y");
				} else if ("2".equals(Dict.frontPage_isBack.get(orderCtrType))) {
					orderDTO.setIsBackCtrType("Y");
				} else if ("3".equals(Dict.frontPage_isBack.get(orderCtrType))) {
					orderDTO.setIsSpecialCtrType("Y");
				}
			}


			//获取  可查询的订单状态
			getOrderStatusForFrontPage(orderDTO, orderCtrType,orderSonCtrType);

			// 判断产品类型 pTypeList
			if(null == orderDTO.getpTypeList()){
				orderDTO.setpTypeList("02,03,06,07");
			}
			if("无跟进人订单".equals(orderDTO.getoFlowerName())){
				orderDTO.setoFlowerName("y");
			}
			page.setTotalCount(orderServiceImpl.queryOrderCountByGaiZao(orderDTO));

			orderDTO.setBegin(page.getStartIndex());
			orderDTO.setEnd(page.getPageSize());
			List<OrderByGaiZaoDTO> listOrder = orderServiceImpl.queryOrderListByGaiZao(orderDTO);


			Future future = null;
			for (final OrderByGaiZaoDTO orderByGaiZaoDTO : listOrder) {
				future = es.submit(new Runnable() {
					@Override
					public void run() {
						try {
							//获取 三件套 状态 （01:未提交审核 02提交审核  未审核  03:提交审核 审核成功  04:提交审核 审核失败）
							getPhoStatusForOrderId(orderByGaiZaoDTO);

							//获取合同 状态 "01"; //待申请 "02"; //已申请 "03"; //已寄出 "04"; //已回收
							getContractStatusForOrderId(orderByGaiZaoDTO);

							//判断是否可以申请后端
							orderByGaiZaoDTO.setBackApplyStatus(checkBackApply(orderByGaiZaoDTO.getId(),orderByGaiZaoDTO.getoStatus()));
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});

			}

			//获取   状态的数量
			Map<String,Integer> statusMap =  new HashMap<String, Integer>();
			if(Dict.frontPage_key.containsKey(orderCtrType) ){
				String frontKey_order_status = Dict.frontPage_key.get(orderCtrType);
				String[] frontKey_order_status_list = frontKey_order_status.split(",");
				String order_status = "";
				int allcount = 0;
				for (int i=0;i<frontKey_order_status_list.length;i++) {

					order_status = Dict.frontKey_order_status.get(frontKey_order_status_list[i]);
					orderDTO.setIdsByorderCtrType(order_status);
					int count =  orderServiceImpl.queryOrderCountByGaiZao(orderDTO);
					allcount = allcount + count;
					statusMap.put(frontKey_order_status_list[i],count);
				}

				statusMap.put("all",allcount);

			}
			if(future!=null)
				future.get();
			resultMap.setAttribute("statusMap", statusMap);
			resultMap.setAttribute("orderList", listOrder);
			resultMap.setAttribute("page",page);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}

	private boolean checkBackApply( String orderId,Integer oStatus) throws SQLException {
		FpOrderCostDTO fpOrderCostTmp = new FpOrderCostDTO();
		fpOrderCostTmp.setOrderId(orderId);
		fpOrderCostTmp.setCostType("\""+ Dict.OrderCostDTO.STATUS_HD_JY+"\",\"" + Dict.OrderCostDTO.STATUS_HD_HDFH + "\",\"" + Dict.OrderCostDTO.STATUS_HD_TX + "\",\"" + Dict.OrderCostDTO.STATUS_HD_SCBT + "\",\"" + Dict.OrderCostDTO.STATUS_HD_OTHER + "\"");
		fpOrderCostTmp.setDeleteTag("1");
		List<FpOrderCostDTO> fpOrderCostTmpList = fpOrderCostService.queryList(fpOrderCostTmp);

		int backStartCount = 0;
		int backEndCount = 0;
		for ( FpOrderCostDTO orderCost : fpOrderCostTmpList){
            if("start".equals(orderCost.getCostStatus())){
                backStartCount ++;
            }else {
                backEndCount++;
            }
        }
		if(backStartCount > 0 ){
           return false;
        }else if (backEndCount >= 2){
			return false;
        }else if(oStatus == 330 || oStatus == 360){
			return true;
        }else{
			return false;
		}
	}

	private void getOrderStatusForFrontPage(OrderByGaiZaoDTO orderDTO, String orderCtrType,String orderSonCtrType) {
		 if(StringUtils.isNotBlank(orderSonCtrType) &&  Dict.frontKey_order_status.containsKey(orderSonCtrType)){
			orderDTO.setIdsByorderCtrType(Dict.frontKey_order_status.get(orderSonCtrType));
			return;
		}else if(StringUtils.isNotBlank(orderCtrType) && Dict.frontPage_key.containsKey(orderCtrType) ){
            String frontKey_order_status = Dict.frontPage_key.get(orderCtrType);
            String[] frontKey_order_status_list = frontKey_order_status.split(",");
            String order_status = "";
            for (int i=0;i<frontKey_order_status_list.length;i++) {
                if(i==0) {
                    order_status = order_status + Dict.frontKey_order_status.get(frontKey_order_status_list[i]);
                }else if(i>0 ){
                    order_status = order_status + ","+Dict.frontKey_order_status.get(frontKey_order_status_list[i]);
                }
            }

            orderDTO.setIdsByorderCtrType(order_status);

        }
	}

	private void getContractStatusForOrderId(OrderByGaiZaoDTO orderByGaiZaoDTO) throws SQLException {
		FpFaUserContractDTO fpFaUserContract = new FpFaUserContractDTO();
		fpFaUserContract.setOrderId(orderByGaiZaoDTO.getId());
		fpFaUserContract = fpFaUserContractService.queryListGetFirst(fpFaUserContract);

		if(fpFaUserContract != null && StringUtils.isNotBlank(fpFaUserContract.getContractStatus())){
			orderByGaiZaoDTO.setContractStatus(fpFaUserContract.getContractStatus());
		}

		if(StringUtils.isBlank(orderByGaiZaoDTO.getContractStatus())){
			orderByGaiZaoDTO.setContractStatus(Dict.UserContractDTO.STATUS_CONTRACT_01);
		}
	}

	//获取 三件套 状态
	private void getPhoStatusForOrderId(OrderByGaiZaoDTO orderByGaiZaoDTO) throws SQLException {
		OrderPhoVO orderPhoVO = new OrderPhoVO();
		// 查询订单是否上传了资料
		orderPhoVO.setoId(orderByGaiZaoDTO.getId().toString());
		orderPhoVO.setpId(orderByGaiZaoDTO.getoProjectId().toString());
		orderPhoVO.setpType(orderByGaiZaoDTO.getoPType());
		List<Map<String, Object>> queryOrderPho = orderPhoServiceImpl.queryOrderPho(orderPhoVO);

		String phoStatus = Constants.order_data_pho_rev_no;
		Map<String,String> map = new HashMap<String,String>();
		for(Map<String, Object> phoMap: queryOrderPho){
			if( phoMap == null || phoMap.get("oPhoStatus") == null){
				map.put("01", "01");
				continue;
			}
			map.put(phoMap.get("oPhoStatus").toString(), "01");
		}

		if(map.containsKey(Constants.order_data_pho_rev_no)){
			phoStatus = Constants.order_data_pho_rev_no;
			orderByGaiZaoDTO.setPhoFlag(phoStatus);
		}else if(map.containsKey(Constants.order_data_pho_rev_fail)){
			phoStatus = Constants.order_data_pho_rev_fail;
			orderByGaiZaoDTO.setPhoFlag(phoStatus);
		}else if(map.containsKey(Constants.order_data_pho_rev_yes) ){
			phoStatus = Constants.order_data_pho_rev_yes;
			orderByGaiZaoDTO.setPhoFlag(phoStatus);
		}else if(map.containsKey(Constants.order_data_pho_rev_success) && !map.containsKey(Constants.order_data_pho_rev_yes)){
			phoStatus = Constants.order_data_pho_rev_success;
			orderByGaiZaoDTO.setPhoFlag(phoStatus);
		}else{
			//默认
			orderByGaiZaoDTO.setPhoFlag(phoStatus);
		}
	}

	/**
	 * 0726ddclyh-订单更新
	 * 订单更新方法
	 */
	@RequestMapping("/orderStatus.shtml")
	@ResponseBody
	public ResultMap  orderStatus(HttpServletRequest request,HttpServletResponse response,OrderByGaiZaoDTO orderDTO,FpOrderCostDTO fpOrderCost){

		String updateInfo = request.getParameter("updateInfo");
		Integer orderStatus = orderDTO.getoStatus()== null?0:orderDTO.getoStatus();
		Integer backStatus = orderDTO.getoBackStatus()== null?0:orderDTO.getoBackStatus();

		DTOdateSet.setUpdateInfo(fpOrderCost, request.getSession());
		DTOdateSet.setCreateInfo(fpOrderCost, request.getSession());
		try{


            //订单不存在直接返回0 修改状态失败
            if(orderDTO.getId() == null){
                resultMap.setStatus(STATUS.FAILE);
                resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
                return resultMap;
            }

			// 获取本订单  数据库状态
			OrderVO orderVo=new OrderVO();
			orderVo.setOrderId(orderDTO.getId());
			List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);
			if(listOrder.size()>0){
				orderVo = listOrder.get(0);
			}


			//订单不存在直接返回0 修改状态失败
			if(orderVo == null){
				log.error("order is not exist!");
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			DTOdateSet.setUpdateInfo(orderDTO, request.getSession());

			//1、(渠道部) 预约中待审核  (点击修改信息-修改  客户姓名，订单金额)
			if(Dict.OrderStatusDTO.STATUS_110 == orderStatus && StringUtils.isNotBlank(updateInfo) && "true".equals(updateInfo)) {
				log.info("in orderStatus 110-updateInfo begin!");
				resultMap =  updateOrderStatus110(orderDTO, orderVo);
				log.info("in orderStatus 110-updateInfo end!");
				return resultMap;
			}else
			//2、(渠道部) 点击预约成功 （预约中待审核110 -> 预约成功待打款130  成交价格、订单备注）
			   //或者 (产品部) 点击审核通过
			if(Dict.OrderStatusDTO.STATUS_130 == orderStatus){

				log.info("in orderStatus 110->130 begin!");
				orderServiceImpl.updateOrderStatus130(orderDTO,orderVo);
				log.info("in orderStatus 110->130 end!");

			}else
			//2-1、(渠道部) 点击预约成功 （预约中待审核110 -> 成交价待审核120  成交价格、订单备注）
			if(Dict.OrderStatusDTO.STATUS_120 == orderStatus){

				log.info("in orderStatus 110->120 begin!");
				orderServiceImpl.updateOrderStatus120(orderDTO,orderVo);
				log.info("in orderStatus 110->120 end!");

			}else
			//2-2、(产品部) 点击审核不通过   取消预约  订单失败  失败原因
			if(Dict.OrderStatusDTO.STATUS_888 == orderStatus || Dict.OrderStatusDTO.STATUS_140 == orderStatus || Dict.OrderStatusDTO.STATUS_999 == orderStatus){

				log.info("in orderStatus 120->140 begin!");
				orderServiceImpl.updateOrderStatus888(orderDTO,orderVo);
				log.info("in orderStatus 120->140 end!");

			}else
			//3、(渠道部) 点击已经打款（预约成功待打款130 -> 已打款待确认220  结佣账户）
			if(Dict.OrderStatusDTO.STATUS_220 == orderStatus){

				log.info("in orderStatus 130->220 begin!");
				orderServiceImpl.updateOrderStatus220(orderDTO,orderVo,fpOrderCost);
				log.info("in orderStatus 130->220 end!");

			}else
			//4、(产品部)点击确认打款（已打款待确认220 -> 确认打款、待佣金到账240 ）
			if(Dict.OrderStatusDTO.STATUS_240 == orderStatus){

				log.info("in orderStatus 220->240 begin!");
				resultMap = orderServiceImpl.updateOrderStatus240(orderDTO,orderVo);
				log.info("in orderStatus 220->240 end!");
				if(resultMap.getStatus().equals(ResultMap.STATUS.FAILE)){
					return resultMap;
				}

			}else
			//5、(产品部) 点击确认佣金到账（确认打款、待佣金到账240 -> 佣金到账、待结佣310 ）
			if(Dict.OrderStatusDTO.STATUS_310 == orderStatus){

				log.info("in orderStatus 240->310 begin!");
				orderServiceImpl.updateOrderStatus310(orderDTO,orderVo,fpOrderCost);
				log.info("in orderStatus 240->310 end!");

			}else
			//5、(财务部) 点击确认结佣（佣金到账、待结佣310 -> 已结佣、待确认320 ）
			if(Dict.OrderStatusDTO.STATUS_320 == orderStatus){

				log.info("in orderStatus 240->310 begin!");
				orderServiceImpl.updateOrderStatus320(orderDTO,orderVo,fpOrderCost);
				log.info("in orderStatus 240->310 end!");

			}else
			//6、(渠道部) 点击确认佣金到账（已结佣、待确认320 -> 结佣结束330 ）
			if(Dict.OrderStatusDTO.STATUS_330 == orderStatus){

				log.info("in orderStatus 320->330 begin!");
				orderServiceImpl.updateOrderStatus330(orderDTO,orderVo);
				log.info("in orderStatus 320->330 end!");

			}else
			//7、(产品部) 点击交易结束（结佣结束330 ->交易结束360 ）//判断合同回收、报单审核通过
			if(Dict.OrderStatusDTO.STATUS_360 == orderStatus){

				//1、判断 报单是否全部审核通过
				if(DateUtil.parseDateString(orderPreTime,"yyyy-MM-dd").before(orderVo.getCreateDate())){
					if (checkOrderPho(orderDTO)){
						//还有附件未通过审核!!!!
						resultMap.setStatus(STATUS.FAILE);
						resultMap.setStatusCode(ResultCode.STATUS_CODE_ORDERCONFIRM_ERROR);
						return resultMap;
					}
				}
				//2、判断 合同是否已经回收
				FpFaUserContractDTO fpFaUserContract = new FpFaUserContractDTO();
				fpFaUserContract.setOrderId(orderVo.getOrderId());
				fpFaUserContract = fpFaUserContractService.queryListGetFirst(fpFaUserContract);
				if(fpFaUserContract == null || !Dict.UserContractDTO.STATUS_CONTRACT_05.equals(fpFaUserContract.getContractStatus())){
					resultMap.setStatus(STATUS.FAILE);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_2012);
					return resultMap;
				}

				//3、订单结束操作
				log.info("in orderStatus 330->360 begin!");
				orderServiceImpl.updateOrderStatus360(orderDTO,orderVo);
				log.info("in orderStatus 330->360 end!");

			}else
			//8、(渠道部) 点击申请后端结佣（  241 后端结佣、待审核 ）
			if(Dict.OrderStatusDTO.STATUS_back_241 == backStatus){

				//判断订单状态是否已经结佣完成  交易结束

				if(!(orderVo.getoStatus() == Dict.OrderStatusDTO.STATUS_360 || Dict.OrderStatusDTO.STATUS_330 == orderVo.getoStatus() )){
					// 前端未完成结佣 -不能申请后端结佣
					resultMap.setStatus(STATUS.FAILE);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_2013);
					return resultMap;
				}
				log.info("in orderBackStatus 241 begin!");
				orderServiceImpl.updateOrderBackStatus241(orderDTO,orderVo,fpOrderCost);
				log.info("in orderBackStatus 241 end!");

			}else
			//8-1、(产品部) 点击申请后端结佣（  231 审核不通过）
			 if(Dict.OrderStatusDTO.STATUS_back_231 == backStatus){
					log.info("in orderBackStatus 231 begin!");
					orderServiceImpl.updateOrderBackStatus231(orderDTO,orderVo);
					log.info("in orderBackStatus 231 end!");
			}else
			 //9、(产品部) 点击申请后端结佣（   后端结佣、待审核 241->上游佣金已结佣 261）
			 if(Dict.OrderStatusDTO.STATUS_back_261 == backStatus){
				 log.info("in orderBackStatus 241 -> 261 begin!");
				 orderServiceImpl.updateOrderBackStatus261(orderDTO,orderVo);
				 log.info("in orderBackStatus 241 -> 261 end!");
			 }else
			//10、(产品部) 点击申请后端结佣（   上游佣金已结佣 261 ->佣金到账、待结佣311）
			if(Dict.OrderStatusDTO.STATUS_back_311 == backStatus){

				log.info("in orderBackStatus 261->311 begin!");
				orderServiceImpl.updateOrderBackStatus311(orderDTO,orderVo,fpOrderCost);
				log.info("in orderBackStatus 261->311 end!");

			}else
			//11、(财务部) 点击确认结佣（   佣金到账、待结佣311 -> 已结佣、待确认 321）
			if(Dict.OrderStatusDTO.STATUS_back_321 == backStatus){

				log.info("in orderBackStatus 311->321 begin!");
				orderServiceImpl.updateOrderBackStatus321(orderDTO,orderVo,fpOrderCost);
				log.info("in orderBackStatus 311->321 end!");

			}else
			//12、(销售部) 点击确认佣金到账（   已结佣、待确认 321 -> 结佣完成 331 ）
			if(Dict.OrderStatusDTO.STATUS_back_331 == backStatus){

				log.info("in orderBackStatus 321->331 begin!");
				orderServiceImpl.updateOrderBackStatus331(orderDTO,orderVo);
				log.info("in orderBackStatus 321->331 end!");

			}else{

			    //没有可处理的订单状态
                resultMap.setAttribute("oStatus",orderStatus);
                resultMap.setStatus(STATUS.FAILE);
                resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
                return resultMap;
            }

			//成功 交易通知  订单流程改造后，交易通知入库 start----
			FaNoticeDTO notice = new FaNoticeDTO();
			DTOdateSet.setCreateInfo(notice, request.getSession());
			DTOdateSet.setUpdateInfo(notice, request.getSession());

			sendOrderNotice(orderDTO.getId(),orderDTO.getoStatus(),orderDTO.getoBackStatus(), notice);
			// 订单流程改造后，交易通知入库 end----

			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("update order status error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}

	private void sendOrderNotice(String orderId, Integer oStatus,Integer oBackStatus, FaNoticeDTO notice) throws Exception {

		if(oStatus == null){
			return;
		}
		notice.setOrderId(orderId);
		// 状态修改成功后、添加通知消息
		log.info("前端状态修改成功后、添加通知消息:"+oStatus);
		log.info("后端状态修改成功后、添加通知消息:"+oBackStatus);
		//switch (null == orderDTO.getoStatus()?orderDTO.getoBackStatus() : orderDTO.getoStatus()) {
		switch (oStatus) {
            case 130:
                // 130：预约成功；
                notice.setType("01");
                break;
            case 210:
                // 210：合同已寄出：
                notice.setType("02");
                break;
            case 140:
                // 140：预约失败：
                notice.setType("03");
                break;
            case 888:
                // 888：订单失败：
                notice.setType("04");
                break;
/*            case 240:
                // 240：确认打款：
                notice.setType("05");
                break;*/
            case 320:
                // 320：已返佣：
                notice.setType("06");
                break;
            case 321:
                // 321：已返佣(后端)：
                notice.setType("07");
                break;
            case 360:
                // 360：交易结束：
                notice.setType("08");
                break;
            default:
                notice.setType("0");
                break;
        }
		if (!notice.getType().equals("0")) {
            faNoticeService.addFaOrderNotice(notice);
        }
	}

	@RequestMapping("/orderDetail.shtml")
	@ResponseBody
	public ResultMap orderDetail(HttpServletRequest request,
									  HttpServletResponse response,OrderVO orderVo ) {

		try{

			if(orderVo.getOrderId() == null ){
				log.error("queryOrderDetailByGaiZao check parameter:id error");
				resultMap.setStatus(STATUS.ERROR);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			String role =   request.getParameter("role");//角色

			List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);

			if(listOrder.size()>0){
				orderVo = listOrder.get(0);
			}

			for(OrderVO orderVO:listOrder){
				//获取产品  价格区间信息
				List<FpProjectRabate> rebateList = projectServiceImpl.getProductProfitRebateList(orderVO.getoProjectId());
				orderVO.setRebateList(rebateList);

				//获取订单 流水信息
				List<OrderFlowDTO> orderFlowList = orderServiceImpl.queryOrderFlowList(orderVO.getOrderId());
				orderVO.setOrderFlowList(orderFlowList);


				//获取 订单费用信息
				FpOrderCostDTO fpOrderCost = new FpOrderCostDTO();
				fpOrderCost.setOrderId(orderVO.getOrderId());
				fpOrderCost.setDeleteTag("1");
				// fpOrderCost.setCostType("\""+Dict.OrderCostDTO.STATUS_QD_JY+"\",\""+Dict.OrderCostDTO.STATUS_QD_SYJK+"\"");
				List<FpOrderCostDTO> orderCostList = fpOrderCostService.queryList(fpOrderCost);

				//订单费用信息-赋值
				getOrderCostByOrderId(orderCostList,orderVO,role);

				//根据不同的角色看不同的信息
				checkOrderRole(request, orderVO);

				//二次结佣信息
				List<FpOrderCostDTO> list = orderCostList;
				List<FpOrderCostDTO> backList = new ArrayList<FpOrderCostDTO>();
				for (FpOrderCostDTO bean:list) {
					if(Dict.OrderCostDTO.STATUS_HD_JY_INFO.indexOf(bean.getCostType())>=0){
						backList.add(bean);
					}
				}
				resultMap.setAttribute("backList", backList);

				//判断是否可以申请后端
				orderVO.setBackApplyStatus(checkBackApply(orderVO.getOrderId(),orderVO.getoStatus()));

			}
			BankCardVO cardVO = new BankCardVO();
			cardVO.setUserId(orderVo.getoFAId());
			List<BankCardVO> bankCardVOs = bankCardServiceImpl.queryBankCardList(cardVO);

			resultMap.setAttribute("orderDetail", orderVo);
			resultMap.setAttribute("bankCardList", bankCardVOs);

			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query order list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}


		return resultMap;
	}

	private void checkOrderRole(HttpServletRequest request, OrderVO orderVO) {
		List<FpOrderCostDTO> list = orderVO.getOrderCostList();
		List<FpOrderCostDTO> listRemove = new ArrayList<FpOrderCostDTO>();
		String role =   request.getParameter("role");//角色

		if(StringUtils.isNotBlank(role)){

            for (FpOrderCostDTO bean :list){
                if(role.indexOf("qd") >= 0 && bean.getCostType().indexOf("SYJK") >= 0){
                    listRemove.add(bean);
                }
                if(role.indexOf("cp") >= 0 && bean.getCostType().indexOf("SYJK") < 0){
                    bean.setBankName(null);
                    bean.setCardNumber(null);
                    bean.setUserName(null);
                }
            }
        }
		if(listRemove.size() > 0){
            list.removeAll(listRemove);
        }
	}

	private void getOrderCostByOrderId(List<FpOrderCostDTO> orderCostList,OrderVO orderVO,String role) throws SQLException {

		List<FpOrderCostDTO> orderCostListTmp = new ArrayList<FpOrderCostDTO>();

		Map<String,FpOrderCostDTO>  orderCostMap =  new HashMap<String, FpOrderCostDTO>();
		int i= 1;
		for (FpOrderCostDTO bean:orderCostList){
			if(bean.getCostType().indexOf("QD") >= 0 ){
				orderCostMap.put(bean.getCostType(),bean);
				continue;
			}
			if(bean.getCostType().indexOf("HD_SYJK") >= 0 ){
				orderCostMap.put(bean.getCostType()+"_"+i++,bean);
				continue;
			}
			if(bean.getCostType().indexOf("HD_CWJY") >= 0 ){
				if(bean.getRelatedId()!= null) {
					orderCostMap.put(bean.getRelatedId().toString(), bean);
				}
				continue;
			}
			orderCostListTmp.add(bean);
		}
		List<FpOrderCostDTO> orderCostListResult = new ArrayList<FpOrderCostDTO>();

		if(orderCostMap.containsKey(Dict.OrderCostDTO.STATUS_QD_SYJK)){
			orderCostListResult.add(orderCostMap.get(Dict.OrderCostDTO.STATUS_QD_SYJK));
		}
		if(orderCostMap.containsKey(Dict.OrderCostDTO.STATUS_QD_JY)){
			if(orderCostMap.containsKey(Dict.OrderCostDTO.STATUS_QD_CWJY)){
				FpOrderCostDTO cwjy = orderCostMap.get(Dict.OrderCostDTO.STATUS_QD_CWJY);
				FpOrderCostDTO jy = orderCostMap.get(Dict.OrderCostDTO.STATUS_QD_JY);
				jy.setCostAmount(cwjy.getCostAmount());
				jy.setOtherFunds(cwjy.getOtherFunds());
				jy.setOtherRemark(cwjy.getOtherRemark());
				jy.setActivityFunds(cwjy.getActivityFunds());
				jy.setActivityRemark(cwjy.getActivityRemark());
				orderCostListResult.add(jy);
			}else{
				if(StringUtils.isBlank(role) || role.indexOf("cp") < 0) {
					orderCostListResult.add(orderCostMap.get(Dict.OrderCostDTO.STATUS_QD_JY));
				}
			}
		}
		for (int j = 0; j < orderCostListTmp.size(); j++) {
			FpOrderCostDTO query = orderCostListTmp.get(j);
			if(orderCostMap.containsKey(Dict.OrderCostDTO.STATUS_HD_SYJK+"_"+(j+1))){
				orderCostListResult.add(orderCostMap.get(Dict.OrderCostDTO.STATUS_HD_SYJK+"_"+(j+1)));
			}
			if(orderCostMap.containsKey(query.getId().toString())){
				FpOrderCostDTO cwjy = orderCostMap.get(query.getId().toString());
				query.setCostAmount(cwjy.getCostAmount());
				query.setOtherFunds(cwjy.getOtherFunds());
				query.setOtherRemark(cwjy.getOtherRemark());
				query.setActivityFunds(cwjy.getActivityFunds());
				query.setActivityRemark(cwjy.getActivityRemark());
				orderCostListResult.add(query);

			}else{
				if(StringUtils.isBlank(role) || role.indexOf("cp") < 0) {
					orderCostListResult.add(query);
				}
			}
		}

		orderVO.setOrderCostList(orderCostListResult);
	}

	private boolean checkOrderPho(OrderByGaiZaoDTO orderDTO) throws SQLException {
		OrderPhoVO orderPhoVO=new OrderPhoVO();
		orderPhoVO.setoId(orderDTO.getId()+"");
		Map<String, Object> queryOrderPhoConfirm = orderPhoServiceImpl.queryOrderPhoConfirm(orderPhoVO);
		int fpodIdCount=Integer.parseInt(queryOrderPhoConfirm.get("fpodId")+"");
		int fopIdCount=Integer.parseInt(queryOrderPhoConfirm.get("fopId")+"");
		if(fpodIdCount!=fopIdCount){
            log.info("还有附件未通过审核!!!!");
			return true;
        }
		return false;
	}

	@Transactional(rollbackFor=Exception.class)
	private ResultMap updateOrderStatus110(OrderByGaiZaoDTO orderDTO, OrderVO orderVo) throws Exception {
		log.info("  in orderStatus  110  begin.............");

		log.info("预约已提交  可以修改  客户姓名，订单金额                              客户id:" + orderVo.getoCId());

		//修改客户
		ClientUserBaseDTO clientUpdate = new ClientUserBaseDTO();
		clientUpdate.setId(orderVo.getoCId());
		clientUpdate.setcName(orderDTO.getoCName());
		clientService.updateClientUserBase(clientUpdate);

		log.info("预约已提交  可以修改  客户姓名，订单金额 | 修改客户信息成功！ updateClientUserBase SUCCESS");

		log.info("预约已提交  可以修改  客户姓名，订单金额 |订单金额:" + orderDTO.getoAmount());

		log.info("预约已提交  可以修改  客户姓名，订单金额|产品id:" + orderVo.getoProjectId());

		//获取产品（销售、核心、成本）
		ProductDetailPageDTO productDetailPageDTO = projectServiceImpl.getProductDetailViewByprice(orderVo.getoProjectId());


		//判断订单金额是否合法
		if (!isTureOrderAmount(productDetailPageDTO, orderDTO.getoAmount(), resultMap)) {
            return resultMap;
        }

		OrderBaseDTO order = new OrderBaseDTO();

		if (!"01".equals(productDetailPageDTO.getCorpType())) {

            order = getCurrentRebateAmountInfo(productDetailPageDTO, orderDTO.getoAmount(), order);

        }


		OrderByGaiZaoDTO updateOrderByGaiZaoDTO = new OrderByGaiZaoDTO();
		updateOrderByGaiZaoDTO.setUpdateBy(orderDTO.getUpdateBy());
		updateOrderByGaiZaoDTO.setUpdateDate(orderDTO.getUpdateDate());
		updateOrderByGaiZaoDTO.setId(orderDTO.getId());
		updateOrderByGaiZaoDTO.setoRebateRate(order.getRebateRate());
		updateOrderByGaiZaoDTO.setoBackRebateRate(order.getBackRebateRate());
		updateOrderByGaiZaoDTO.setoSellingPrice(order.getSellingPrice());
		updateOrderByGaiZaoDTO.setoBackSellingPrice(order.getBackSellingPrice());
		updateOrderByGaiZaoDTO.setoRebateAmount(order.getRebateAmount());
		updateOrderByGaiZaoDTO.setoSellingRebate(order.getSellingRebate());
		updateOrderByGaiZaoDTO.setoBackRebateAmount(order.getBackRebateAmount());
		updateOrderByGaiZaoDTO.setoBackSellingRebate(order.getBackSellingRebate());
		updateOrderByGaiZaoDTO.setoAmount(orderDTO.getoAmount());


		orderServiceImpl.updateOrderStatusNow(updateOrderByGaiZaoDTO,orderVo);

		log.info("预约已提交  可以修改  客户姓名，订单金额 |修改订单详细价格成功！ updateOrderStatusByGaiZao SUCCESS");

		resultMap.setStatus(STATUS.SUCCESS);
		resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		return resultMap;
	}

	/**
	 * 订单流程改造
	 * 订单更新方法
	 */
	@RequestMapping("/updateOrderStatusByGaiZao.shtml")
	@ResponseBody
	public ResultMap  updateOrderStatusByGaiZao(HttpServletRequest request,HttpServletResponse response,OrderByGaiZaoDTO orderDTO){
		try{
			
			String updateInfo = request.getParameter("updateInfo");
			
			// 预约已提交  可以修改  客户姓名，订单金额
			if(null != orderDTO.getoStatus() && orderDTO.getoStatus() == 110 && StringUtils.isNotBlank(updateInfo) && "true".equals(updateInfo)){
				
				log.info("预约已提交  可以修改  客户姓名，订单金额                                 begin.............");
				
				OrderVO orderVo=new OrderVO();
				orderVo.setOrderId(orderDTO.getId());
				List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);
				if(listOrder.size()>0){
					orderVo = listOrder.get(0);
				}
				
				log.info("预约已提交  可以修改  客户姓名，订单金额                              客户id:"+orderVo.getoCId());
				
				ClientUserBaseDTO clientUpdate =  new ClientUserBaseDTO();
				clientUpdate.setId(orderVo.getoCId());
				clientUpdate.setcName(orderDTO.getoCName());
				clientService.updateClientUserBase(clientUpdate);
				
				log.info("预约已提交  可以修改  客户姓名，订单金额 | 修改客户信息成功！ updateClientUserBase SUCCESS");
				
				log.info("预约已提交  可以修改  客户姓名，订单金额 |订单金额:"+orderDTO.getoAmount());
				
				log.info("预约已提交  可以修改  客户姓名，订单金额|产品id:"+orderVo.getoProjectId());
				
				//获取产品（销售、核心、成本）
				ProductDetailPageDTO productDetailPageDTO  = projectServiceImpl.getProductDetailViewByprice(orderVo.getoProjectId());
				
				
				//判断订单金额是否合法
				if(!isTureOrderAmount(productDetailPageDTO,orderDTO.getoAmount(),resultMap)){
					return resultMap;
				}
				
				OrderBaseDTO order = new OrderBaseDTO();
				
				if(!"01".equals(productDetailPageDTO.getCorpType())){
					
					order = getCurrentRebateAmountInfo(productDetailPageDTO,orderDTO.getoAmount(),order);
					
				}
				
				log.info("预约已提交  可以修改  客户姓名，订单金额 |返佣率 rebateRate:"+order.getRebateRate());
				log.info("预约已提交  可以修改  客户姓名，订单金额 |后端返佣率 backRebateRate:"+order.getBackRebateRate());
				log.info("预约已提交  可以修改  客户姓名，订单金额 |销售价 sellingPrice:"+order.getSellingPrice());
				log.info("预约已提交  可以修改  客户姓名，订单金额 |后端销售价  backSellingPrice:"+order.getBackSellingPrice());
				
				log.info("预约已提交  可以修改  客户姓名，订单金额 |返佣额  rebateAmount:"+order.getRebateAmount());
				log.info("预约已提交  可以修改  客户姓名，订单金额 |销售返佣额 sellingRebate:"+order.getSellingRebate());
				log.info("预约已提交  可以修改  客户姓名，订单金额 |返佣额 backRebateAmount:"+order.getBackRebateAmount());
				log.info("预约已提交  可以修改  客户姓名，订单金额 |销售返佣额backSellingRebate:"+order.getBackSellingRebate());
				log.info("预约已提交  可以修改  客户姓名，订单金额 |预期年化收益 annualRevenue:"+order.getAnnualRevenue());
				
				OrderByGaiZaoDTO updateOrderByGaiZaoDTO = new OrderByGaiZaoDTO();
				updateOrderByGaiZaoDTO.setId(orderDTO.getId());
				updateOrderByGaiZaoDTO.setoRebateRate(order.getRebateRate());
				updateOrderByGaiZaoDTO.setoBackRebateRate(order.getBackRebateRate());
				updateOrderByGaiZaoDTO.setoSellingPrice(order.getSellingPrice());
				updateOrderByGaiZaoDTO.setoBackSellingPrice(order.getBackSellingPrice());
				updateOrderByGaiZaoDTO.setoRebateAmount(order.getRebateAmount());
				updateOrderByGaiZaoDTO.setoSellingRebate(order.getSellingRebate());
				updateOrderByGaiZaoDTO.setoBackRebateAmount(order.getBackRebateAmount());
				updateOrderByGaiZaoDTO.setoBackSellingRebate(order.getBackSellingRebate());
				updateOrderByGaiZaoDTO.setoAmount(orderDTO.getoAmount());
				
				orderServiceImpl.updateOrderStatusByGaiZao(updateOrderByGaiZaoDTO);
				
				log.info("预约已提交  可以修改  客户姓名，订单金额 |修改订单详细价格成功！ updateOrderStatusByGaiZao SUCCESS");
				
				resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
				return resultMap;
				
				
			}
			
			// 如果订单没有走完，则不能结束交易
			if(null != orderDTO.getoStatus() && orderDTO.getoStatus() == 360){
				OrderVO orderVo=new OrderVO();
				orderVo.setOrderId(orderDTO.getId());
				List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);
				if(listOrder.size()>0){
					orderVo = listOrder.get(0);
				}
				// 不为空																非无后端 											非后端已走完
				if(null != orderVo.getoBackStatus() && orderVo.getoBackStatus() !=361 && orderVo.getoBackStatus() != 331 ){
					log.info("后端流程未走完");
					resultMap.setStatus(STATUS.FAILE);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_ORDECLOSED_ERROR);
					return resultMap;
				}
			}
			// 订单如果附件没有审核成功，则不能确认合同
			if(null != orderDTO.getoStatus() && orderDTO.getoStatus()==350){
				
				OrderVO orderVo=new OrderVO();
				orderVo.setOrderId(orderDTO.getId());
				List<OrderVO> listOrder = orderServiceImpl.queryOrderList(orderVo);
				if(listOrder.size()>0){
					orderVo = listOrder.get(0);
				}
				if(DateUtil.parseDateString(orderPreTime,"yyyy-MM-dd").before(orderVo.getCreateDate())){
					OrderPhoVO orderPhoVO=new OrderPhoVO();
					orderPhoVO.setoId(orderDTO.getId()+"");
					Map<String, Object> queryOrderPhoConfirm = orderPhoServiceImpl.queryOrderPhoConfirm(orderPhoVO);
					int fpodIdCount=Integer.parseInt(queryOrderPhoConfirm.get("fpodId")+"");
					int fopIdCount=Integer.parseInt(queryOrderPhoConfirm.get("fopId")+"");
					if(fpodIdCount!=fopIdCount){
						log.info("还有附件未通过审核!!!!");
						resultMap.setStatus(STATUS.FAILE);
						resultMap.setStatusCode(ResultCode.STATUS_CODE_ORDERCONFIRM_ERROR);
						return resultMap;
					}
				}
				
			}
			DTOdateSet.setUpdateInfo(orderDTO, request.getSession());
			StringBuffer stringBuffer = new StringBuffer()
											.append("order ")
											.append(orderDTO.getId())
											.append("status update to ")
											.append(orderDTO.getoStatus())
											.append(",back status to")
											.append(orderDTO.getoBackStatus());
			logsServiceImpl.addLog("updateOrderStatus order id :"+orderDTO.getId(), stringBuffer.toString(), orderDTO.getUpdateBy());
			
			if(orderServiceImpl.updateOrderStatusByGaiZao(orderDTO)<1){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}

			// 订单流程改造后，交易通知入库 start----
			FaNoticeDTO notice = new FaNoticeDTO();
			DTOdateSet.setCreateInfo(notice, request.getSession());
			DTOdateSet.setUpdateInfo(notice, request.getSession());
			sendOrderNotice(orderDTO.getId(),orderDTO.getoStatus(),orderDTO.getoBackStatus(), notice);

			// 订单流程改造后，交易通知入库 end----
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("update order status error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	/**
	 * 【渠道部】查询【我的相关订单】
	 */
	@RequestMapping("/queryQuDaoMyOrderListByGaiZao.shtml")
	@ResponseBody
	public ResultMap  queryQuDaoMyOrderListByGaiZao(HttpServletRequest request,HttpServletResponse response,OrderByGaiZaoDTO orderDTO,Pager page){
		HttpSession session = request.getSession();
		UserInfoDTO user = (UserInfoDTO)session.getAttribute(DTOdateSet.user);
		orderDTO.setDepartmentName(Dict.department_name_qudao);
		orderDTO.setoFlowerName(user.getUsername());
		orderDTO.setSearchCriteriaQD(orderDTO.getSearchCriteria());

		try {
			List<String> systemUserIds = faUserServiceImpl.queryFaUserSubUserId(user.getUserId(),"机构");
			systemUserIds.add(user.getUserId());
			orderDTO.setSystemUserIds(systemUserIds);
			if(systemUserIds.size()>0){
				orderDTO.setoFlowerName(null);
			}
		} catch (SQLException e) {
			log.error("queryFaUserSubUserId error", e);
		}

		return queryOrderListByGaiZao(request, response, orderDTO, page);
	}
	
	
	/**
	 * 【渠道部】查询【全部订单】
	 */
	@RequestMapping("/queryQuDaoAllOrderListByGaiZao.shtml")
	@ResponseBody
	public ResultMap  queryQuDaoAllOrderListByGaiZao(HttpServletRequest request,HttpServletResponse response,OrderByGaiZaoDTO orderDTO,Pager page){
		orderDTO.setDepartmentName(Dict.department_name_qudao);
		orderDTO.setSearchCriteriaQD(orderDTO.getSearchCriteria());
		return queryOrderListByGaiZao(request, response, orderDTO, page);
	}
	
	
	/**
	 * 【产品部】查询【我的相关订单】
	 */
	@RequestMapping("/queryChanPinMyOrderListByGaiZao.shtml")
	@ResponseBody
	public ResultMap  queryChanPinMyOrderListByGaiZao(HttpServletRequest request,HttpServletResponse response,OrderByGaiZaoDTO orderDTO,Pager page){
		HttpSession session = request.getSession();
		UserInfoDTO user = (UserInfoDTO)session.getAttribute(DTOdateSet.user);
		orderDTO.setDepartmentName(Dict.department_name_chanpin);
		orderDTO.setoManagerName(user.getUsername());
		orderDTO.setSearchCriteriaCP(orderDTO.getSearchCriteria());
		return queryOrderListByGaiZao(request, response, orderDTO, page);
	}
	
	
	/**
	 * 【产品部】查询【全部订单】
	 */

	@RequestMapping("/queryChanPinAllOrderListByGaiZao.shtml")
	@ResponseBody
	public ResultMap  queryChanPinAllOrderListByGaiZao(HttpServletRequest request,HttpServletResponse response,OrderByGaiZaoDTO orderDTO,Pager page){
		orderDTO.setDepartmentName(Dict.department_name_chanpin);
		orderDTO.setSearchCriteriaCP(orderDTO.getSearchCriteria());
		return queryOrderListByGaiZao(request, response, orderDTO, page);
	}
	
	/**
	 * 【财务部高级】查询【订单】
	 */
	
	@RequestMapping("/queryCaiWuMyOrderListByGaiZao.shtml")
	@ResponseBody
	public ResultMap  queryCaiWuMyOrderListByGaiZao(HttpServletRequest request,HttpServletResponse response,OrderByGaiZaoDTO orderDTO,Pager page){
		orderDTO.setDepartmentName(Dict.department_name_caiwu);

		if("06".equals( orderDTO.getOrderCtrType() )) {
			orderDTO.setIdsByorderCtrType("350,360");
		}

		ResultMap resultMap = queryOrderListByGaiZao(request, response, orderDTO, page);
		// 列表页面 计算进出账信息
		// calculateIncomeAndExpenditure
		if(resultMap.getAttribute("orderList") != null){
			List<OrderByGaiZaoDTO> listOrder = (List<OrderByGaiZaoDTO>) resultMap.getAttribute("orderList");
			for (OrderByGaiZaoDTO orderByGaiZaoDTO : listOrder) {
				orderByGaiZaoDTO.calculateIncomeAndExpenditure();
			}
			resultMap.setAttribute("orderList", listOrder);
		}else{
			resultMap.setAttribute("orderList", Collections.EMPTY_LIST);
		}

		
		return resultMap;
	}
	
	/**
	 * 【财务部普通】查询【订单】
	 */
	
	@RequestMapping("/queryCaiWuAllOrderListByGaiZao.shtml")
	@ResponseBody
	public ResultMap  queryCaiWuAllOrderListByGaiZao(HttpServletRequest request,HttpServletResponse response,OrderByGaiZaoDTO orderDTO,Pager page){
		orderDTO.setDepartmentName(Dict.department_name_caiwu);
		//搜索添加
		orderDTO.setSearchCriteriaQD(orderDTO.getSearchCriteria());
		return queryOrderListByGaiZao(request, response, orderDTO, page);
	}
	
	
	/**
	 * 查询产品负责人接口
	 */
	
	@RequestMapping("/queryOrderOwnerUserList.shtml")
	@ResponseBody
	public ResultMap queryOrderOwnerUserList(HttpServletRequest request, HttpServletResponse response){
		try {
			List<OrderManagerUserVO> list = null;

			list = orderServiceImpl.queryOrderOwnerUserList();

			resultMap.setAttribute("list", list);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (SQLException e) {
			log.error("queryOrderManagerUsers error", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		return resultMap;
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/orderCsv.shtml")
	public void orderCsv(HttpServletRequest request,
			HttpServletResponse response,OrderVO orderVo,Pager page) {
		
		log.info("in orderCsv begin!");
		
		ZipOutputStream zos = null;
		List list = null;
        try{
            log.info("Begin orderCsv list!");
            orderVo.setPageSize(5000);
            int count = orderServiceImpl.queryOrderAllInfoCount(orderVo);
            
            //如果查询总数量 《= PageSize，直接生成CSV
            if(count <= orderVo.getPageSize()){
            	log.info("Begin orderCsv list《=!"+count+":"+orderVo.getPageSize());
            	 list = orderServiceImpl.queryOrderList(orderVo);
                 CsvExportUtil.doCsvExport(response, list);
                 return ;
            }
            
            //如果查询总数量  > PageSize， 打成zip
            response.reset();
            response.setHeader("Content-Disposition",
                    "attachment;filename=orderExport.zip");
            zos = new ZipOutputStream(response.getOutputStream());
            int i = 1;
            do {
            	orderVo.setPage(i++);
    			orderVo.setEnd(orderVo.getPageSize());
                list = orderServiceImpl.queryOrderList(orderVo);
                CsvExportUtil.doCsvExportForZip(zos, list,"order"+orderVo.getBegin()+"-"+(orderVo.getEnd()+orderVo.getBegin())+".csv");
			} while (list.size() == orderVo.getPageSize());
            
            zos.closeEntry();
            zos.finish();
            log.info("in orderCsv End!");
        }catch(Exception e){
            log.error("orderCsv error !",e);
        }finally {
			if (zos != null) {
				try {
					zos.close();
				} catch (IOException e) {
				}
			}
		}

        return;
    }
	
	/**
	 * 根据交易额度决定返佣比率及额度
	 * @return
	 */
	private OrderBaseDTO getCurrentRebateAmountInfo(ProductDetailPageDTO productDetailPageDTO,BigDecimal amount,OrderBaseDTO orderDto){
		List<ProductProfitAndRebateVO> list = productDetailPageDTO.getProfitAndRebateList();
		BigDecimal expectSaleAmount = productDetailPageDTO.getExpectSaleAmount();
		
		 //	wap_jee_1.3 
		 // 		annualRevenue 预期收益Double 改成文本框 String 
		 // 	 	author lisu
		//预期年化收益
		String annualRevenue =  productDetailPageDTO.getAnnualRevenueExpect();
		
		BigDecimal rebateAmount = new BigDecimal(-1);
		BigDecimal common = new BigDecimal(0.01);
		BigDecimal sellingRebate = new BigDecimal(-1);
		BigDecimal costRebate  = new BigDecimal(-1);
		BigDecimal coreRebate  = new BigDecimal(-1);
		BigDecimal backRebateAmount = new BigDecimal(-1);
		BigDecimal backSellingRebate = new BigDecimal(-1);
		BigDecimal backCostRebate  = new BigDecimal(-1);
		BigDecimal backCoreRebate  = new BigDecimal(-1);
		
		BigDecimal max = new BigDecimal(-1);
		Double rebateMax = null; 
		BigDecimal sellingPriceMax = new BigDecimal(-1);
		BigDecimal costPriceMax = new BigDecimal(-1);
		BigDecimal corePriceMax = new BigDecimal(-1);
		Double backRebateMax = null; 
		BigDecimal backSellingPriceMax = new BigDecimal(-1);
		BigDecimal backCostPriceMax = new BigDecimal(-1);
		BigDecimal backCorePriceMax = new BigDecimal(-1);
		for(ProductProfitAndRebateVO vo:list){
			if(vo.getEndAmount().compareTo(max) > 0){
				max = vo.getEndAmount();
				rebateMax = vo.getRebate();
				sellingPriceMax = vo.getSellingPrice();
				costPriceMax = vo.getCostPrice();
				corePriceMax = vo.getCorePrice();
				backRebateMax = vo.getBackRabate();
				backSellingPriceMax = vo.getBackSellingPrice();
				backCostPriceMax = vo.getCostBackPrice();
				backCorePriceMax = vo.getCoreBackPrice();
			}
		}
		
		log.info("max rebate amount is "+max);
		log.info("max rebate is "+ rebateMax);
		
		for(ProductProfitAndRebateVO vo:list){
			//起始金额
			BigDecimal start =vo.getStartAmount();
			//结束金额
			BigDecimal end = vo.getEndAmount();
			//返佣 挂网价
			Double rebate = vo.getRebate();
			//销售价
			BigDecimal  sellingPrice = vo.getSellingPrice();
			//核心价
			BigDecimal  corePrice = vo.getCorePrice();
			//成本价
			BigDecimal  costPrice = vo.getCostPrice();
			// ————订单流程改造 后端价格
			// 后端 返佣 挂网价
			Double backRebate = vo.getBackRabate();
			// 后端 销售价
			BigDecimal  backSellingPrice = vo.getBackSellingPrice();
			// 后端 核心价
			BigDecimal  backCorePrice = vo.getCoreBackPrice();
			// 后端 成本价
			BigDecimal  backCostPrice = vo.getCostBackPrice();
			// 是否协议，0：否，1是
			String isAgreement = vo.getpIsAgreement();
			
			if(amount.intValue() >= max.intValue() && amount.intValue()<=expectSaleAmount.intValue()){
				//最大边界值
				if(!vo.getRebateIsRatio()){
					rebateAmount= BigDecimal.valueOf(rebateMax);
					orderDto.setRebateRate( new BigDecimal(-1));
					backRebateAmount = BigDecimal.valueOf(backRebateMax);
					orderDto.setBackRebateRate(new BigDecimal(-1));
				}else{
					rebateAmount = BigDecimal.valueOf(rebateMax*0.01).multiply(amount);
					orderDto.setRebateRate(BigDecimal.valueOf(rebateMax));
					backRebateAmount = BigDecimal.valueOf(backRebateMax*0.01).multiply(amount);
					orderDto.setBackRebateRate(BigDecimal.valueOf(backRebateMax));
				}
				sellingRebate = sellingPriceMax==null?null:sellingPriceMax.multiply(common).multiply(amount);//销售返佣额
				coreRebate = corePriceMax==null?null:corePriceMax.multiply(common).multiply(amount);//核心返佣额
				costRebate = costPriceMax==null?null:costPriceMax.multiply(common).multiply(amount);//成本返佣额
				backSellingRebate = sellingPriceMax==null?null:backSellingPriceMax.multiply(common).multiply(amount);//后端销售返佣额
				backCoreRebate = corePriceMax==null?null:backCorePriceMax.multiply(common).multiply(amount);//后端核心返佣额
				backCostRebate = costPriceMax==null?null:backCostPriceMax.multiply(common).multiply(amount);//后端成本返佣额
				
				orderDto.setSellingPrice(sellingPriceMax);
				orderDto.setCorePrice(corePriceMax);
				orderDto.setCostPrice(costPriceMax);
				orderDto.setBackSellingPrice(backSellingPriceMax);
				orderDto.setBackCorePrice(backCorePriceMax);
				orderDto.setBackCostPrice(backCostPriceMax);
				
				orderDto.setRebateAmount(rebateAmount);
				orderDto.setSellingRebate(sellingRebate);
				orderDto.setCoreRebate(coreRebate);
				orderDto.setCostRebate(costRebate);
				orderDto.setBackRebateAmount(backRebateAmount);
				orderDto.setBackSellingRebate(backSellingRebate);
				orderDto.setBackCoreRebate(backCoreRebate);
				orderDto.setBackCostRebate(backCostRebate);
				orderDto.setAnnualRevenue(annualRevenue);
				return orderDto;
			}
			//判断预约金额是否在此区间
			if(start.intValue()<=amount.intValue()&&amount.intValue()<end.intValue()){
				if(!vo.getRebateIsRatio()){
					rebateAmount= BigDecimal.valueOf(rebate);
					orderDto.setRebateRate(new BigDecimal(-1));
					backRebateAmount= BigDecimal.valueOf(backRebate);
					orderDto.setBackRebateRate(new BigDecimal(-1));
				}else{
					rebateAmount = BigDecimal.valueOf(rebate*0.01).multiply(amount);
					orderDto.setRebateRate(BigDecimal.valueOf(rebate));
					backRebateAmount = BigDecimal.valueOf(backRebate*0.01).multiply(amount);
					orderDto.setBackRebateRate(BigDecimal.valueOf(backRebate));
				}
				//计算  销售返佣额| 核心返佣额| 成本返佣额
				sellingRebate = sellingPrice == null?null:sellingPrice.multiply(common).multiply(amount);//销售返佣额
				coreRebate = corePrice == null?null:corePrice.multiply(common).multiply(amount);//核心返佣额
				costRebate = costPrice == null?null:costPrice.multiply(common).multiply(amount);//成本返佣额
				backSellingRebate = backSellingPrice == null?null:backSellingPrice.multiply(common).multiply(amount);//后端销售返佣额
				backCoreRebate = backCorePrice == null?null:backCorePrice.multiply(common).multiply(amount);//后端核心返佣额
				backCostRebate = backCostPrice == null?null:backCostPrice.multiply(common).multiply(amount);//后端成本返佣额
				
				orderDto.setSellingPrice(sellingPrice);
				orderDto.setCorePrice(corePrice);
				orderDto.setCostPrice(costPrice);
				orderDto.setBackSellingPrice(backSellingPrice);
				orderDto.setBackCorePrice(backCorePrice);
				orderDto.setBackCostPrice(backCostPrice);
				
				orderDto.setRebateAmount(rebateAmount);
				orderDto.setSellingRebate(sellingRebate);
				orderDto.setCoreRebate(coreRebate);
				orderDto.setCostRebate(costRebate);
				orderDto.setBackRebateAmount(backRebateAmount);
				orderDto.setBackSellingRebate(backSellingRebate);
				orderDto.setBackCoreRebate(backCoreRebate);
				orderDto.setBackCostRebate(backCostRebate);
				orderDto.setIsAgreement(isAgreement);
//				orderDto.setRebateAmount(rebateAmount);
				orderDto.setAnnualRevenue(annualRevenue);
				return orderDto;
			}
		}
		return orderDto;
	}
	/**
	 * 
	* @Title: isTureOrderAmount 
	* @Description: 判断是否为合法的订单金额，订单金额=产品起购金额+n*累进金额  (n为大于等于的整数) 且订单金额应该不大预售金额-已经实际销售金额
	* @param @return    
	* @return boolean   
	* @throws
	 */
	private boolean isTureOrderAmount(ProductDetailPageDTO productDetailPageDTO,BigDecimal amount,ResultMap result){
		
		//订单金额
		BigDecimal orderAmount = amount;
		//产品起购金额
		BigDecimal minimumAmount = productDetailPageDTO.getMinimumAmount();
		//产品实际销售金额
		BigDecimal signingAmount = productDetailPageDTO.getSigningAmount();
		//产品预售金额
		BigDecimal expectSaleAmount = productDetailPageDTO.getExpectSaleAmount();
		//产品累进金额
		BigDecimal progressiveAmount = productDetailPageDTO.getpProgressiveAmount();
		
		
		log.info("orderAmount:"+orderAmount);
		log.info("minimumAmount:"+minimumAmount);
		log.info("signingAmount:"+signingAmount);
		log.info("expectSaleAmount:"+expectSaleAmount);
		log.info("progressiveAmount:"+progressiveAmount);
		//订单金额减去起购金额的值
		BigDecimal multiple = orderAmount.subtract(minimumAmount);
		
		//比起购金额还小
		if(multiple.signum()<0){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultCode.STATUS_CODE_AMOUNT_MIN_ERROR);
			result.setMessage("购买额低于起拍金额，起拍额为:"+minimumAmount);
			return false;
		}
		
		//不是累进金额的倍数
		if(multiple.remainder(progressiveAmount).compareTo(new BigDecimal(0)) != 0){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultCode.STATUS_CODE_AMOUNT_PROGRESSIVE_ERROR);
			result.setMessage("累进购买金额有误。");
			return false;
		}
		
		BigDecimal moreAount =  expectSaleAmount.subtract(signingAmount);
		//订单金额超过可预售金额
		if((moreAount.subtract(orderAmount)).signum()<0){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultCode.STATUS_CODE_AMOUNT_MAX_ERROR);
			result.setMessage("可预订金额为:"+moreAount);
			return false;
		}
		
		return  true;
	}
	
	/***
	 * 查询订单-昨日我的团队的业绩月度业绩
	 * @param request
	 */
	@RequestMapping("/queryOrderOwnerUserCountAmount.shtml")
	@ResponseBody
	public ResultMap queryOrderOwnerUserCountAmount(HttpServletRequest request) {
		
		ResultMap result = new ResultMap();
		log.info("in queryOrderOwnerUserCountAmount begin!");
        try{
        	
        	List<Map<String, Object>> queryOrderOwnerUserCountAmount = orderServiceImpl.queryOrderOwnerUserCountAmount();
        	//昨日签单之星
        	Map<String,Object> yesterdayMax = new HashMap<String, Object>();
        	//本月签单之星
        	Map<String,Object> monthMax = new HashMap<String, Object>();
        	//自己的昨日签单
        	Map<String,Object> self = new HashMap<String, Object>();
        	//当前登录用户id
			UserInfoDTO userinfo = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
			String currentUserId=userinfo.getUserId();
			
			long monthSumAmount=0;
			
        	for (Map<String, Object> map : queryOrderOwnerUserCountAmount) {
        		BigDecimal yesterdayAmount = (BigDecimal)map.get("yesterdayAmount");
        		BigDecimal yesterdayAmountMax = (BigDecimal)(yesterdayMax.get("yesterdayAmount")==null?new BigDecimal(0):yesterdayMax.get("yesterdayAmount"));
        		if(yesterdayAmount.compareTo(yesterdayAmountMax)==1){
        			yesterdayMax=map;
        		}
        		BigDecimal monthAmount =  (BigDecimal)map.get("monthAmount");
        		BigDecimal monthAmountMax = (BigDecimal)(monthMax.get("monthAmount")==null?new BigDecimal(0):monthMax.get("monthAmount"));
        		if(monthAmount.compareTo(monthAmountMax)==1){
        			monthMax=map;
        		}
        		String userId= map.get("userId")+"";
        		if(currentUserId.equals(userId)){
        			self=map;
        		}
        		//统计本月总销售业绩
        		monthSumAmount+=monthAmount.longValue();
        	}
        	
        	result.setAttribute("yesterdayMax",yesterdayMax);
        	result.setAttribute("monthMax",monthMax);
        	result.setAttribute("self",self);
        	result.setAttribute("monthSumAmount",monthSumAmount);
        	
            log.info("in queryOrderOwnerUserCountAmount End!");
            result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
        }catch(Exception e){
            log.error("queryOrderOwnerUserCountAmount error !",e);
            result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
        }

        return result;
    }
}